package com.example.myapplication.adapters;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import com.bumptech.glide.Glide;
import com.example.myapplication.R;
import com.example.myapplication.models.Course;

import java.util.List;

public class CourseAdapter extends RecyclerView.Adapter<CourseAdapter.CourseViewHolder> {

    private List<Course> courses;
    private OnCourseClickListener listener;

    public CourseAdapter(List<Course> courses, OnCourseClickListener listener) {
        this.courses = courses;
        this.listener = listener;
    }

    @NonNull
    @Override
    public CourseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.item_course, parent, false);
        return new CourseViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull CourseViewHolder holder, int position) {
        Course course = courses.get(position);

        Glide.with(holder.ivCourseImage.getContext())
                .load(course.getImageUrl())
                .placeholder(R.drawable.ic_launcher_background)
                .into(holder.ivCourseImage);

        holder.tvCourseTitle.setText(course.getTitle());
        holder.tvInstructor.setText("讲师: " + course.getInstructor());
        holder.tvDifficulty.setText("难度: " + course.getDifficulty());
        holder.tvRating.setText("评分: " + course.getRating());

        holder.itemView.setOnClickListener(v -> {
            if (listener != null) {
                listener.onCourseClick(course);
            }
        });
    }

    @Override
    public int getItemCount() {
        return courses == null ? 0 : courses.size();
    }

    static class CourseViewHolder extends RecyclerView.ViewHolder {
        ImageView ivCourseImage;
        TextView tvCourseTitle;
        TextView tvInstructor;
        TextView tvDifficulty;
        TextView tvRating;

        public CourseViewHolder(@NonNull View itemView) {
            super(itemView);
            ivCourseImage = itemView.findViewById(R.id.iv_course_image);
            tvCourseTitle = itemView.findViewById(R.id.tv_course_title);
            tvInstructor = itemView.findViewById(R.id.tv_instructor);
            tvDifficulty = itemView.findViewById(R.id.tv_difficulty);
            tvRating = itemView.findViewById(R.id.tv_rating);
        }
    }

    public interface OnCourseClickListener {
        void onCourseClick(Course course);
    }
}